package cn.com.mma.mobile.tracking.util;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.content.Context;
import cn.com.mma.mobile.tracking.api.Global;
import cn.com.mma.mobile.tracking.bean.SDK;

/**
 * config配置文件相关工具类
 * 
 * @author lincoln
 * 
 */
public class SdkConfigUpdateUtil {
	/**
	 * 初始化Sdk配置文件
	 * 
	 * 
	 * @return
	 */
	public static void initSdkConfigResult(Context context, String configUrl) {
		sdk = getNewestSDK(context, configUrl);
	}

	/**
	 * 获取最新的sdk文件
	 * 
	 * @return
	 */
	private static SDK getNewestSDK(Context context, String configUrl) {
		SDK sdkNewest;
		if (JudgeUpdateAccordingDate(context)) {
			sdkNewest = dealUpdateConfig(context, configUrl);
			if (sdkNewest == null) {
				sdkNewest = getSDKFromPreferences(context);
			}
		} else {
			sdkNewest = getSDKFromPreferences(context);
			if (sdkNewest == null) {
				sdkNewest = dealUpdateConfig(context, configUrl);
			}
		}

		return sdkNewest;
	}

	/**
	 * 如果当前是 wifi 环境，每天更新一次配置文件，如果当前是 2G / 3G 环境，每隔 3 天更新一次配置文件
	 */
	private static boolean JudgeUpdateAccordingDate(Context context) {
		boolean result = true;
		long interValTimeWifi = 24 * 60 * 60 * 1000;
		long interValTimeMobile = 3 * interValTimeWifi;

		// long interValTimeWifi = 1 * 60 * 1000;
		// long interValTimeMobile = 2 * interValTimeWifi;
		long currentTime = System.currentTimeMillis();
		long lastUpdateTime = SharedPreferencedUtil.getLong(context, SharedPreferencedUtil.SP_NAME_OTHER, SharedPreferencedUtil.SP_OTHER_KEY_UPDATE_TIME);
		Logger.d("mma_config lastUpdateTimeStamp:" + lastUpdateTime);
		// 每天更新一次:时间间隔大于1天则更新
		Logger.d("mma_config wifi:" + CommonUtil.isWifiConnected(context) + " | " + ((currentTime - lastUpdateTime >= interValTimeWifi)));
		Logger.d("mma_config mobile:" + CommonUtil.isMobileConnected(context) + " | " + ((currentTime - lastUpdateTime >= interValTimeMobile)));
		boolean isWifiUpdate = (CommonUtil.isWifiConnected(context) && (currentTime - lastUpdateTime >= interValTimeWifi));
		// 每三天更新一次：时间间隔大于3天则更新
		boolean isMobileUpdate = (CommonUtil.isMobileConnected(context) && (currentTime - lastUpdateTime >= interValTimeMobile));
		if (isWifiUpdate || isMobileUpdate) {
			result = true;
			SharedPreferencedUtil.putLong(context, SharedPreferencedUtil.SP_NAME_OTHER, SharedPreferencedUtil.SP_OTHER_KEY_UPDATE_TIME, currentTime);
		} else {
			result = false;
		}
		Logger.d("mma_config File need Update：" + result);
		return result;
	}

	/**
	 * 网络更新config.xml文件后的
	 * 
	 * @param configUrl
	 */
	public static SDK dealUpdateConfig(Context context, String configUrl) {
		SDK sdk = null;
		String response = getConfigFromNetWork(configUrl);
		if (response != null) {
			try {
				sdk = XmlUtil.doParser(new ByteArrayInputStream(response.getBytes("UTF-8")));
				if (sdk != null &&sdk.companies != null &&sdk.companies.size() > 0) {
					SharedPreferencedUtil.putString(context, SharedPreferencedUtil.SP_NAME_CONFIG, SharedPreferencedUtil.SP_CONFIG_KEY_FILE, response);
					Logger.d("mma_网络更新sdkconfig.xml成功");
				}
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}

		return sdk;
	}

	/**
	 * 从SharedPreferences中获取sdkconfig.xml文件,转换成SDK对象
	 * 
	 * @param context
	 * @return
	 */
	public static SDK getSDKFromPreferences(Context context) {
		try {
			String valueString = SharedPreferencedUtil.getString(context, SharedPreferencedUtil.SP_NAME_CONFIG, SharedPreferencedUtil.SP_CONFIG_KEY_FILE);
			return valueString != null ? XmlUtil.doParser(new ByteArrayInputStream(valueString.getBytes())) : null;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 网络请求sdkconfig.xml文件
	 * 
	 * @return
	 */
	private static String getConfigFromNetWork(String configUrl) {
		if (configUrl == null)
			return null;
		try {
			URL url = new URL(configUrl);
			HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
			urlConnection.setConnectTimeout(10000);
			urlConnection.connect();
			InputStream inputStream = urlConnection.getInputStream();
			BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
			StringBuffer buffer = new StringBuffer();
			String line = "";
			while ((line = in.readLine()) != null) {
				buffer.append(line);
			}
			inputStream.close();
			return buffer.toString();
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 设置SDK
	 * 
	 * @param sdk
	 */
	private static void setSdk(SDK sdk) {
		Logger.d("mma_setSdk");
		if (sdk != null) {
			try {
				if (sdk.offlineCache.length != null && !"".equals(sdk.offlineCache.length))
					Global.OFFLINECACHE_LENGTH = Integer.parseInt(sdk.offlineCache.length);
				if (sdk.offlineCache.queueExpirationSecs != null && !"".equals(sdk.offlineCache.queueExpirationSecs))
					Global.OFFLINECACHE_QUEUEEXPIRATIONSECS = Integer.parseInt(sdk.offlineCache.queueExpirationSecs);
				if (sdk.offlineCache.timeout != null && !"".equals(sdk.offlineCache.timeout))
					Global.OFFLINECACHE_TIMEOUT = Integer.parseInt(sdk.offlineCache.timeout);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	private static SDK sdk = null;

	public static SDK getSdk(Context context) {
		if (sdk == null || sdk.companies == null) {
			// 没有获取配置文件成功，则使用app内置配置文件
			try {
				sdk = XmlUtil.doParser(context.getAssets().open(XmlUtil.XMLFILE));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		setSdk(sdk);
		return sdk;
	}

}
